<template>
  <div>
     <h1>添加账号</h1>
   <!-- 内容部分 -->
        <div class="box">
          <el-form :model="formData" :rules="rules" ref="formRef" >
       <el-form-item label="账号" prop="account">
         <el-input v-model="formData.account"></el-input>
       </el-form-item>
       <el-form-item label="密码" prop="password">
         <el-input v-model="formData.password"></el-input>
       </el-form-item>
       <el-form-item label="用户组" prop="userGroup">
         <!-- <el-input v-model="formData.userGroup"></el-input> -->
         <el-select v-model="formData.userGroup" placeholder="请选择用户组">
             <el-option value="超级管理员">超级管理员</el-option>
             <el-option value="普通管理员">普通管理员</el-option>
</el-select>
       </el-form-item>
      <el-form-item>
            <el-button type="primary" @click="addAccount">添加</el-button>
            <el-button type="default" @click="resetForm">重置</el-button>
        </el-form-item>
     </el-form>
        </div>
  </div>
</template>

<script setup>
import { ref,reactive } from 'vue'
import {add }from '@/views/api/account'
import { serverUrl } from '@/views/utils/common'; // 导入服务器地址
import { ElMessage } from 'element-plus';
const formRef = ref(null)
const formData = reactive({
  account: '',
  password: '',
  userGroup: '',
})
const validateAccount = (rule, value, callback) => {
  //rule :整个input的所有的规则  
  //value:当前input的值
  //callback:回调函数，如果校验通过，callback() ，  必须只要写一次验证通过
  //        校验不通过，callback(new Error('错误信息'))
  let reg = /^([a-z]|[0-9]){4,11}$/
  if (reg.test(value)) {
    callback()
  } else {
    callback(new Error('请输入正确的账号'))
  }

}
const validatePassword = (rule, value, callback) => {
  let reg = /^([a-z]|[0-9]){4,11}$/
  if (reg.test(value)) {
    callback()
  } else {
    callback(new Error('请输入正确的密码'))
  }
}

//校验规则
const rules = {
  account: [
   { required: true, message: '账号不能为空', trigger: 'blur' },
    { validator: validateAccount, trigger: 'blur' }
  ],
  password:[
  { required: true, message: '密码不能为空', trigger: 'blur' },
    {validator: validatePassword, trigger: 'blur' }
  ],
   userGroup: [
    { required: true, message: '请选择用户组', trigger: 'blur' }
  ]
}
//添加按钮
const addAccount = async () => {
  formRef.value.validate(async (res) =>{
    if(res){
      let {code ,msg} = await add(formData)
      if(code == 0){
        ElMessage.success(msg);
        formRef.value.resetFields()
      }
    }else{
      ElMessage.error(msg);
    }
  })
}
//重置按钮
const resetForm = () => {
  formRef.value.resetFields()
}
</script>

<style lang="scss" scoped>
  .box{width: 400px;
    margin-top:20px;
  }
</style>